import axios from 'axios'
import Qs from 'qs'
import store from '@/store'
import router from '@/router'
import {getToken, getTokenKey} from '@/utils/auth'
import { Message, MessageBox } from 'element-ui' // 引用element-ui的加载和消息提示组件

let isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const $axios = axios.create({
  // 设置超时时间
  timeout: 30000,
  // 基础url，会在请求url中自动添加前置链接
  baseURL: process.env.VUE_APP_BASE_API
})

// 请求拦截器
$axios.interceptors.request.use(config => {
    if (getToken()) {
      // 每个请求头部都添加上token
      let tokenKey = getTokenKey()
      config.headers[tokenKey] = getToken()
    }
    return config
  }, error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
$axios.interceptors.response.use(response => {
    // 获取ajax请求状态码，获取不到就当成成功
    const code = response.data.code || 0;
    const message = response.data.message || '未知错误！';
    if (code === 401) { // 自定义码等于401说明会话已失效
      if (!isRelogin.show) {
        MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
              cancelButtonText: '取消',
              confirmButtonText: '重新登录',
              type: 'warning'
            }
        ).then(() => {
          // 点击重新登录则先执行登出操作后跳转到登录页
          store.dispatch('user/_clean').then(() => {
            console.log('_clean success');
            router.push({
              path: '/login',
              query: {
                redirect: router.currentRoute.fullPath
              }
            }).then();
          });
        }).catch(() => {
          isRelogin.show = false;
        });
      }
      return Promise.reject('登录状态已过期，请重新登录')
    } else if (code !== 0) {// 不等于200说明发生了错误
      Message({
        message: message,
        type: 'error',
        duration: 2 * 1000
      });
      return Promise.reject(new Error(message));
    } else {
      // 成功的返回
      return Promise.resolve(response.data);
    }
  }, error => {
    let message = error.message;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

// get，post请求方法
export default {
  post(url, data) {
    return $axios({
      method: 'post',
      url: url,
      data: Qs.stringify(data),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  },
  postJSON(url, data) {
    return $axios({
      method: 'post',
      url: url,
      data: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    })
  },
  get(url, query) {
    return $axios({
      method: 'get',
      url: url,
      params: query
    })
  }
}
